<template>
    <div class="jscode">
        <button class="copy-button" @click="copyCode">
            {{ copied ? "COPIED!" : "COPY" }}
        </button>
        <code ref="codeBlock" :class="`language-${language}`">{{ content }}</code>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';
import { useClipboard } from '@vueuse/core'


// 接收 props
const props = defineProps({
    content: {
        type: String,
        required: true,
    },
    language: {
        type: String,
        default: 'JavaScript', // 默认高亮语言
    },
});

const { copy, copied } = useClipboard({ source: props.content })
const codeBlock = ref(null); // 引用代码块

// 高亮代码
const highlightCode = () => {
    if (codeBlock.value) {
        // 检查并移除 dataset.highlighted
        if (codeBlock.value.dataset.highlighted) {
            delete codeBlock.value.dataset.highlighted;
        }
        nextTick(() => {
            hljs.highlightElement(codeBlock.value);
        })
    }
};

// 复制代码功能
const copyCode = () => {
    copy(props.content)
};

// 在组件挂载时高亮代码
onMounted(highlightCode);

// 当内容变化时重新高亮
watch(() => props.content, highlightCode);
</script>

<style scoped>
.jscode {
    --tw-shadow: 7px 7px 15px 0 #000;
    --tw-shadow-colored: 7px 7px 15px 0 var(--tw-shadow-color);
    box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
}

/* 语言标签样式 */
.language-label {
    font-weight: bold;
    text-transform: uppercase;
}

/* 复制按钮样式 */
.copy-button {
    float: right;
    background-color: rgba(0, 0, 0, .3);
    border: none;
    border-radius: 4px;
    padding: 4px 8px;
    color: white;
    cursor: pointer;
    font-size: 12px;
    transition: background-color 0.2s ease-in-out;
}

.copy-button:hover {
    background-color: #357ab8;
}

.copy-button:active {
    background-color: #2b5c93;
}

/* 代码块样式 */
pre {
    margin: 0;
    padding: 16px;
    overflow: auto;
    font-size: 14px;
    font-family: 'Courier New', Courier, monospace;
    background-color: #2d2d2d;
}

code {
    display: block;
    white-space: pre-wrap;
    word-break: break-word;
}
</style>